package com.vinoxm.admin.config.token;

import com.vinoxm.admin.vo.UserVo;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.DefaultUserAuthenticationConverter;

import java.util.LinkedHashMap;
import java.util.Map;

public class JwtCustomAccessTokenConverter extends DefaultAccessTokenConverter {

    public JwtCustomAccessTokenConverter() {
        super.setUserTokenConverter(new CustomerUserAuthenticationConverter());
    }

    private static class CustomerUserAuthenticationConverter extends DefaultUserAuthenticationConverter{
        @Override
        public Map<String, ?> convertUserAuthentication(Authentication authentication) {
            LinkedHashMap<String, Object> response = new LinkedHashMap<>();
            Object principal = authentication.getPrincipal();
            response.put(USERNAME, authentication.getName());
            if (principal instanceof UserVo) {
                response.put("userId", ((UserVo) principal).getId());
            }
            if (authentication.getAuthorities() != null && !authentication.getAuthorities().isEmpty()) {
                response.put(AUTHORITIES, AuthorityUtils.authorityListToSet(authentication.getAuthorities()));
            }
            return response;
        }
    }
}
